<template>
  <span>
    <Container :open.sync="open" :zIndex="100004" @submit="submit">
      <div style="width: 100%;height: 70vh;" class="flex-col imginfoContainer">
        <el-row :gutter="24" class="mb8">
          <el-col :xs="24" :sm="24" :md="6" :lg="3" :xl="3" class="padding-5 flex-row">
            <input type="file" multiple ref="fileInput" style="display: none;" @change="handleFiles">
            <el-button type="primary" size="mini" @click="selectFile">选择文件<i class="el-icon-upload el-icon--right"></i></el-button>
            <el-button type="success" size="mini" @click="addNetWorkImage">添加外链<i class="el-icon-upload el-icon--right"></i></el-button>
            <el-button type="warning" size="mini" @click="addCrawlerLinkImg">选择爬取图片<i class="el-icon-upload el-icon--right"></i></el-button>
          </el-col>
        </el-row>

        <el-row :gutter="24" class="mb8">
          <el-col :xs="24" :sm="24" :md="18" :lg="4" :xl="4" class="padding-5">
            <div class="flex-row">
              <el-select
                v-if="mode === 'add'"
                v-model="batchItemObj.collid"
                filterable
                remote
                :remote-method="remoteMethod"
                placeholder="请选择合集"
                style="width: 100%;"
                class="flex-1"
              >
                <el-option v-for="item in collectOptions" :key="item.id" :label="item.collname" :value="item.id"></el-option>
              </el-select>
              <el-button type="primary" size="mini" @click="addCollec"><i class="el-icon-plus"></i></el-button>
            </div>
          </el-col>
          <el-col :xs="24" :sm="24" :md="18" :lg="6" :xl="4" class="padding-5">
            <el-input v-model="batchItemObj.title" label="标题" placeholder="请输入标题" ></el-input>
          </el-col>
          <el-col :xs="24" :sm="24" :md="18" :lg="6" :xl="4" class="padding-5">
            <el-cascader
              v-model="batchItemObj.allimgtypeid"
              :props="{ checkStrictly: true, value: 'id',label: 'name' }"
              :options="typeList"
              placeholder="请选择分类"
              style="width: 100%;"
            >
            </el-cascader>
          </el-col>
          <el-col :xs="24" :sm="24" :md="18" :lg="4" :xl="4" class="padding-5">
            <Tag v-model="batchItemObj.tag" label="添加标签"/>
          </el-col>
          <el-col :xs="24" :sm="24" :md="18" :lg="4" :xl="4" class="padding-5">
            <el-button type="primary" @click="configUpdate">确认</el-button>
            <el-button @click="restForm">重置</el-button>
          </el-col>
        </el-row>

        <div class="fill-width flex-1" style="min-height: 0;overflow: auto">
          <el-table stripe v-loading="loading" :data="tableList" @selection-change="handleSelectionChange"  @expand-change="expandChange" >
            <el-table-column
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column label="图片" prop="file" width="300">
              <template #default="scope">
                <div v-if="scope.row.isExtImg" class="flex-row justify-center align-center">
                  <el-image
                    v-if="scope.row.extImgUrl.length > 0"
                    class="image"
                    fit="contain"
                    :src="scope.row.extImgUrl"
                    :lazy="true"
                    :preview-src-list="[scope.row.extImgUrl]"
                    style="width: 100px"
                  >
                  </el-image>
                  <el-input v-model="scope.row.extImgUrl" placeholder="请输入一个http地址"></el-input>
                </div>
                <div v-else>
                  <img v-if="mode === 'add'" :src="imagePreviews(scope.row.file)" alt="Image Preview" class="image-preview">
                  <img v-if="mode === 'edit'" :src="getPreviewPath(scope.row.id)" alt="Image Preview" class="image-preview">
                </div>
              </template>
            </el-table-column>

            <el-table-column v-if="mode === 'add'" label="请选择合集" prop="title" :show-overflow-tooltip="true" width="300">
              <template #default="scope">
                <el-select
                  v-model="scope.row.collid"
                  filterable
                  remote
                  :remote-method="remoteMethod"
                  placeholder="请选择合集"
                >
                  <el-option
                    v-for="citem in collectOptions"
                    :key="citem.id"
                    :label="citem.collname"
                    :value="citem.id">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="标题" prop="title" :show-overflow-tooltip="true" >
              <template #default="scope">
                <el-input v-model="scope.row.title" placeholder="请输入标题" style="max-width: 250px"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="图片类型" prop="allimgtypeid" :show-overflow-tooltip="true" width="250" >
              <template #default="scope">
                <el-cascader
                  v-model="scope.row.allimgtypeid"
                  :props="{ checkStrictly: true, value: 'id',label: 'name' }"
                  :options="typeList">
                </el-cascader>
              </template>
            </el-table-column>
            <el-table-column label="图片标签" prop="tag" >
              <template #default="scope">
                <Tag v-model="scope.row.tag"/>
              </template>
            </el-table-column>
            <el-table-column label="显示顺序" prop="ordernum" width="100" >
              <template #default="scope">
                <el-input v-model="scope.row.ordernum" placeholder="请输入显示顺序"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="操作" prop="handle" width="120" fixed="right" v-if="mode !== 'edit'">
              <template #default="scope">
                <div class="fill-width flex-row" style="gap: 5px;">
                  <el-button type="danger" plain icon="el-icon-delete" size="mini" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </Container>

    <CollectionItem ref="collectionItemRef" mode="add" @callBack="collectionItemSuccessCallBack"/>

    <el-dialog :visible.sync="selectImgDialogVisible" width="90%" title="选择爬取任务的图片"
               :z-index="100005" modal-append-to-body :close-on-click-modal="false"
    >
      <div class="fill-width-height dialog-content flex-col">
        <SelectData ref="imageCrawlerRef" class="flex-1" style="min-height: 0;overflow: hidden"/>
        <el-divider style="margin: 0"/>
        <div class="d-flex align-center justify-center">
          <el-button type="primary" @click="configSelect">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </span>
</template>

<script>
import {updateImage, uploadImg} from '@/api/imgManage/image'
import requirePool from '@/utils/requirePool'
import { getList } from "@/api/imgManage/imgType";
import { debounce, listToTree } from '@/utils'
import {getImgCollectPage, getPageList, update} from "@/api/imgManage/imgCollect";
import Container from './Container'
export default {
  name: '',
  components: {
    // Upload: () => import('./upload')
    Container,
    Tag: () => import('../components/tag.vue'),
    SelectData : () => import('@/views/imgManage/imageCrawler/selectData'),
    CollectionItem: () => import('@/views/imgManage/collectionManage/itemForm')
  },
  props: {
    itemObj: {

    },
    mode: {
      type: String,
      default: () => 'add'
    },
    itemObjList: {
      type: Array,
      default: () => []
    }
  },
  watch:{
    itemObj(newVal){
      this.batchItemObj=newVal;
    }
  },
  data() {
    return {

      selectImgDialogVisible: false,
      visible: false,
      htmlUrl: '',
      open: false,
      loading: false,
      loadingOption: false,
      tableList: [],
      typeList: [],
      // tableList2:[{ id: '11' }],
      ids: [],
      single: true,
      multiple: false,
      collectOptions: [],
      batchItemObj: {
        collid: null,
        collcode: null,
        title: null,
        allimgtypeid: null,
        tag: null,
      },
      allObj: { value:'all', label: '全部' ,id:'all', name: '全部' },
      iscollOptions: [
        { value: 0, label: '否' },
        { value: 1, label: '是' }
      ],
      multipleSelection: [],
      childrenList: []
    }
  },
  computed: {
  },
  methods: {
    addCollec(){
      this.$refs.collectionItemRef.handleOpen()
    },
    collectionItemSuccessCallBack(){
      this.remoteMethod()
    },
    addNetWorkImage(){
      this.handleAdd(null,'')
    },
    addCrawlerLinkImg(){
      this.selectImgDialogVisible = true
      this.$nextTick(() => {
        this.$refs.imageCrawlerRef?.initSelectData()
      })
    },
    configSelect: debounce(function() {
      this.$modal.loading("正在处理数据，请稍候...");
      const data = this.$refs.imageCrawlerRef?.getSelectedData() || [];
      const batchSize = 50;
      const totalBatches = Math.ceil(data.length / batchSize);

      const processBatch = (batchIndex) => {
        if (batchIndex >= totalBatches) {
          this.$modal.closeLoading();
          this.selectImgDialogVisible = false;
          return;
        }

        const startIndex = batchIndex * batchSize;
        const endIndex = Math.min(startIndex + batchSize, data.length);
        const batchData = data.slice(startIndex, endIndex);

        batchData.forEach(item => {
          this.handleAdd(null, item.imageSrc);
        });

        setTimeout(() => {
          processBatch(batchIndex + 1);
        }, 50);
      };

      processBatch(0);
    }, 500),
    restForm(){
      this.batchItemObj = {
        collid: null,
        collcode: null,
        title: null,
        allimgtypeid: null,
        tag: null,
      }
    },
    expandChange(row){
      row.isOpenExpand = !row.isOpenExpand
      this.childrenList = []
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.single = selection.length != 1
      this.multiple = !selection.length
      this.multipleSelection = selection;
    },
    handleAdd(file,isExtImgUrl){
      let item = null
      if(this.multipleSelection.length >0 ){
        item = this.multipleSelection[0]
      }
      const itemObj = {
        file: file ? file : null,
        title: null,
        allimgtypeid: null,
        tag: null,
        ordernum: this.tableList.length + 1
      }
      if(isExtImgUrl || isExtImgUrl ===''){
        itemObj.isExtImg = true
        itemObj.extImgUrl = isExtImgUrl
      }
      this.tableList.push(itemObj)
    },
    async remoteMethod(query) {
      this.loadingOption = true;
      const imgCollectionDataList = await getPageList({ collname: query }).then(res => res.rows )
      this.loadingOption = false;
      this.collectOptions = imgCollectionDataList
    },
    async initTypeList(){
      const dataList = await getList({ bustype: 'imgType' }).then(res => res.data )
      dataList.forEach((item) => {
        item.label = item.name
        item.value = item.id
      })
      const treeList = listToTree(dataList,'id','parentid')
      treeList.forEach((item) => {
        if(item?.children?.length === 0){
          delete item.children
        }
      })
      treeList.unshift(this.allObj)
      this.typeList = treeList
    },
    handleDelete(index, row) {
      this.tableList.splice(index, 1);
    },
    // 触发文件选择
    selectFile() {
      this.$refs.fileInput.click();
    },
    // 处理文件选择事件
    handleFiles(event) {
      // 将 FileList 转换为数组
      const selectedFiles = Array.from(event.target.files);
      selectedFiles.forEach(file => this.handleAdd(file))
    },
    isFile(obj) {
      return obj instanceof File;
    },
    getPreviewPath(id){
      return this.$config.urlFormat('/openApi/previewByBussId?bussid=' + id)
    },
    imagePreviews(file){
      if(this.isFile(file)){
        return URL.createObjectURL(file)
      }
      return file
    },
    configUpdate(){
      const dataToBeUpdated = this.multipleSelection?.length === 0 ? this.tableList : this.multipleSelection
      dataToBeUpdated.forEach(item => {
        Object.assign(item, this.batchItemObj)
        item?.children?.forEach(childItem => {
          Object.assign(childItem, this.batchItemObj)
        })
      })
    },
    uuidv4() {
      return ([1e7]+'-'+1e3+'-'+4e3+'-'+8e3+'-'+1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
      );
    },
    addSubmit(){
      // 使用 FormData 来构建请求数据
      const formDataList = []
      const tableList = []
      this.tableList.forEach(item => {
        item.id = this.uuidv4()
        if(item.allimgtypeid instanceof Array){
          item.allimgtypeid = item.allimgtypeid.join(',')
        }
        item.iscoll = 1

        tableList.push(item)
      })
      tableList.forEach(item => {
        const formData = new FormData();
        Object.keys(item).forEach(key => {
          if(key === 'file' && item[key] ){
            formData.append("file", item.file);
          } else if(key === 'collid') {
            formData.append("collid", item.collid);
          } else if( key === 'extImgUrl'){
            formData.append("extImgUrl", item.extImgUrl);
          } else {
            formData.append("imgInfo."+ key, item[key]);
          }
        })
        formDataList.push(formData)
      })
      const task = formDataList.map(formData => {
        return uploadImg(formData)
      })
      this.$modal.loading("正在上传，请稍候...");
      requirePool(task,5).then(res => {
        this.successCallBack()
        this.$modal.closeLoading()
      }).catch(e => {
        this.$modal.closeLoading()
      })
    },
    successCallBack(){
      this.$modal.msgSuccess("操作成功");
      this.$emit('callBack')
      this.open = false
    },
    editSubmit(){
      const submitList = JSON.parse(JSON.stringify(this.tableList))
      submitList.forEach(item => {
        if(item.allimgtypeid instanceof Array){
          item.allimgtypeid = item.allimgtypeid.join(',')
        }
      })
      updateImage(submitList).then(res => {
        this.successCallBack()
      }).catch(e => {
        this.$modal.closeLoading()
      })
    },
    submit(){
      if(this.mode === 'add'){
       return this.addSubmit()
      }
      this.editSubmit()
    },
    init(){
      this.open = true
      if(this.mode === 'add'){
        this.restForm()
        this.tableList = []
      } else if(this.mode === 'edit'){
        this.tableList = this.itemObjList
        this.tableList.forEach(item => {
          if(typeof item.allimgtypeid === 'string'){
            item.allimgtypeid = item.allimgtypeid?.split(',')
          }
          if(item.title === 'null'){
            item.title = ''
          }
          if(item.fileid?.startsWith('http')){
            item.isExtImg = true
            item.extImgUrl = item.fileid;
          }

        })
      }
    }
  },
  mounted() {
    this.initTypeList()
    this.remoteMethod()
  }
}
</script>


<style scoped lang="scss">
.image-preview {
  max-width: 150px;
  max-height: 150px;
  object-fit: cover;
}
.padding-5{
  padding: 5px;
}
.imginfoContainer{
  ::v-deep{
    .el-table__body-wrapper{
      min-height: 300px !important;
    }
  }
}
/* 在样式部分添加以下内容 */
.dialog-content {
  max-height: 80vh; /* 设置最大高度为视口高度的80%，可根据需求调整 */
  height: 80vh;
}

/* 覆盖el-dialog的默认样式，确保不会影响body的滚动 */
::v-deep.el-dialog {
  overflow: hidden; /* 隐藏dialog的溢出内容 */
}
</style>
